package cn.zhixiangsingle.impl.inventoryAlert;

import cn.zhixiangsingle.config.DynamicDataSourceContextHolder;
import cn.zhixiangsingle.dao.inventoryAlert.InventoryAlertMapper;
import cn.zhixiangsingle.dao.site.SiteMapper;
import cn.zhixiangsingle.date.DateUtils;
import cn.zhixiangsingle.entity.base.IsEmptyUtils;
import cn.zhixiangsingle.entity.base.site.SiteData;
import cn.zhixiangsingle.entity.base.site.vo.SiteVO;
import cn.zhixiangsingle.entity.inventoryAlert.dto.InventoryAlertDTO;
import cn.zhixiangsingle.entity.inventoryAlert.vo.InventoryAlertVO;
import cn.zhixiangsingle.pagination.MyStartEndUtil;
import cn.zhixiangsingle.service.inventoryAlert.InventoryAlertService;
import cn.zhixiangsingle.web.responsive.IStatusMessage;
import cn.zhixiangsingle.web.responsive.ResultBean;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author hhp
 * @description 存储异常推送业务
 * @date 2019/11/12 14:24
 * @Copyright: 2019 www.zhixiangyun.net Inc. All rights reserved.
 * 注意：本内容仅限于浙江智飨科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service(version = "1.0.0", interfaceClass = InventoryAlertService.class)
public class InventoryAlertServiceImpl implements InventoryAlertService {
    private static final Logger logger = LoggerFactory
            .getLogger(InventoryAlertServiceImpl.class);
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private InventoryAlertMapper inventoryAlertMapper;
    /**
     *@描述
     *@参数 [inventoryAlertDTO]
     *@返回值 cn.zhixiangsingle.web.responsive.ResultBean
     *@创建人 hhp
     *@创建时间 2019/11/12
     *@修改人和其它信息
     */
    @Override
    public ResultBean findInventoryAlertList(InventoryAlertDTO inventoryAlertDTO) throws Exception {
        ResultBean resultBean = new ResultBean();
        if(IsEmptyUtils.isEmpty(inventoryAlertDTO.getPage())){
            inventoryAlertDTO.setPage(1);
        }
        if (IsEmptyUtils.isEmpty(inventoryAlertDTO.getLimit())){
            inventoryAlertDTO.setLimit(10);
        }
        Integer page = inventoryAlertDTO.getPage();
        Integer limit = inventoryAlertDTO.getLimit();
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<Map<String,Object>> mainLPLs = Lists.newArrayList();
        Integer total = 0;
        int startNum = (page-1)*limit;
        int endNum = startNum+limit;
        ArrayList<Integer> totalAll = Lists.newArrayList();
        inventoryAlertDTO.setId(-1);
        inventoryAlertDTO.setHandleTime("h");
        if(IsEmptyUtils.isEmpty(inventoryAlertDTO.getAlertStatus())){
            inventoryAlertDTO.setAlertStatus("a");
        }
        inventoryAlertDTO.setOccurTime("o");
        inventoryAlertDTO.setUnderTaker("u");
        inventoryAlertDTO.setAffirmant("a");
        inventoryAlertDTO.setExpContext("e");
        if(!IsEmptyUtils.isEmpty(inventoryAlertDTO.getSdIds())){
            String[] sdIds = inventoryAlertDTO.getSdIds().split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for(String sdId:sdIds){
                inventoryAlertDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdId))){
                    siteData = JSON.parseObject(jobj.get(sdId).toString(),SiteData.class);
                }
                inventoryAlertDTO.setPicturePrefix(siteData.getPicturePrefix());
                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){
                    if(IsEmptyUtils.isEmpty(stringBuffer)){
                        stringBuffer.append(sdId);
                    }else{
                        stringBuffer.append(","+sdId);
                    }
                    logger.info("--"+dataSourceName+"--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = inventoryAlertMapper.findInventoryAlertTotal(inventoryAlertDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll,startNum,endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for(int i=0;i<startEndNums.size();i++){
                inventoryAlertDTO.setSdId(Integer.parseInt(sourceNames[i]));
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(),SiteData.class);
                inventoryAlertDTO.setPicturePrefix(siteData.getPicturePrefix());
                logger.info("--"+siteData.getDateSourceName()+"--");
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                inventoryAlertDTO.setStart(startEndNums.get(i).get(0));
                inventoryAlertDTO.setEnd(startEndNums.get(i).get(1)-startEndNums.get(i).get(0));
                inventoryAlertDTO.setSdId(Integer.parseInt(sourceNames[i]));
                inventoryAlertDTO.setSiteName(siteData.getName());
                inventoryAlertDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String,Object>> mainLPList = inventoryAlertMapper.findInventoryAlertList(inventoryAlertDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }else{
            List<SiteVO> userSites = siteMapper.findUserSites(inventoryAlertDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for(SiteVO siteVO:userSites){
                inventoryAlertDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))){
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(),SiteData.class);
                }
                inventoryAlertDTO.setPicturePrefix(siteData.getPicturePrefix());
                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){
                    if(IsEmptyUtils.isEmpty(stringBuffer)){
                        stringBuffer.append(siteVO.getSdId());
                    }else{
                        stringBuffer.append(","+siteVO.getSdId());
                    }
                    logger.info("null sdIds...--"+dataSourceName+"----");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);
                    Integer totalStatus = inventoryAlertMapper.findInventoryAlertTotal(inventoryAlertDTO);
                    total = total + totalStatus;
                    totalAll.add(totalStatus);
                }
            }
            ArrayList<ArrayList<Integer>> startEndNums = MyStartEndUtil.getStartEndArray(totalAll,startNum,endNum);
            String[] sourceNames = stringBuffer.toString().split(",");
            for(int i=0;i<startEndNums.size();i++){
                SiteData siteData = JSON.parseObject(jobj.get(sourceNames[i]).toString(),SiteData.class);
                logger.info("--"+siteData.getDateSourceName()+"--");
                inventoryAlertDTO.setPicturePrefix(siteData.getPicturePrefix());
                inventoryAlertDTO.setSdId(Integer.parseInt(sourceNames[i]));
                DynamicDataSourceContextHolder.setDataSourceType(siteData.getDateSourceName());
                inventoryAlertDTO.setStart(startEndNums.get(i).get(0));
                inventoryAlertDTO.setEnd(startEndNums.get(i).get(1)-startEndNums.get(i).get(0));
                inventoryAlertDTO.setSdId(Integer.parseInt(sourceNames[i]));
                inventoryAlertDTO.setSiteName(siteData.getName());
                inventoryAlertDTO.setSitePhoto(siteData.getPhoto());

                List<Map<String,Object>> mainLPList = inventoryAlertMapper.findInventoryAlertList(inventoryAlertDTO);
                mainLPLs.addAll(mainLPList);
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        resultBean.setSuccess(true);
        resultBean.setResult(mainLPLs);
        resultBean.setTotal(total);
        resultBean.setResultCode(IStatusMessage.SystemStatus.SUCCESS.getCode());
        resultBean.setMsg(IStatusMessage.SystemStatus.SUCCESS.getMessage());
        return resultBean;
    }
    /**
     *@描述
     *@参数 [inventoryAlertDTO]
     *@返回值 java.util.List<cn.zhixiangsingle.web.responsive.ResultBean>
     *@创建人 hhp
     *@创建时间 2019/11/12
     *@修改人和其它信息
     */
    @Override
    public List<ResultBean> getInventoryAlerts(InventoryAlertDTO inventoryAlertDTO) throws Exception {
        StringBuffer stringBufferJson = new StringBuffer();
        InputStream stream = getClass().getClassLoader().getResourceAsStream("json/siteData.json");
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        String line;
        while ((line = br.readLine()) != null) {
            stringBufferJson.append(line);
        }
        JSONObject jobj = JSON.parseObject(stringBufferJson.toString());

        List<ResultBean> mainLPLs = Lists.newArrayList();
        inventoryAlertDTO.setHandleTime("h");
        if(IsEmptyUtils.isEmpty(inventoryAlertDTO.getAlertStatus())){
            inventoryAlertDTO.setAlertStatus("a");
        }
        inventoryAlertDTO.setOccurTime("o");
        inventoryAlertDTO.setUnderTaker("u");
        inventoryAlertDTO.setAffirmant("a");
        inventoryAlertDTO.setExpContext("e");
        String exportTopTitle = "存储异常推送信息-"+DateUtils.formatDate(new Date(),"yyyy-MM-dd")+"导出";
        if(!IsEmptyUtils.isEmpty(inventoryAlertDTO.getSdIds())){
            String[] sdIds = inventoryAlertDTO.getSdIds().split(",");
            for(String sdId:sdIds){
                inventoryAlertDTO.setSdId(Integer.parseInt(sdId));
                String dataSourceName = "";
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdId))){
                    siteData = JSON.parseObject(jobj.get(sdId).toString(),SiteData.class);
                }
                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){
                    logger.info("--"+dataSourceName+"--");
                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

                    inventoryAlertDTO.setSiteName(siteData.getName());

                    Map columnWidth = new HashMap();
                    columnWidth.put(0,5000);
                    columnWidth.put(1,4000);
                    columnWidth.put(2,4000);
                    columnWidth.put(3,3000);
                    columnWidth.put(4,5000);
                    columnWidth.put(5,15000);
                    List<List<String>> topTitles = Lists.newArrayList();
                    List<String> col0 = Lists.newArrayList();
                    List<String> col1 = Lists.newArrayList();
                    List<String> col2 = Lists.newArrayList();
                    List<String> col3 = Lists.newArrayList();
                    List<String> col4 = Lists.newArrayList();
                    List<String> col5 = Lists.newArrayList();
                    col0.add(exportTopTitle);col0.add("日期");
                    col1.add(exportTopTitle);col1.add("承担者昵称");
                    col2.add(exportTopTitle);col2.add("确认者名称");
                    col3.add(exportTopTitle);col3.add("状态");
                    col4.add(exportTopTitle);col4.add("处理时间");
                    col5.add(exportTopTitle);col5.add("异常描述");
                    topTitles.add(col0);
                    topTitles.add(col1);
                    topTitles.add(col2);
                    topTitles.add(col3);
                    topTitles.add(col4);
                    topTitles.add(col5);
                    ResultBean resultBean = new ResultBean();
                    resultBean.setMsg(siteData.getName());
                    resultBean.setObj(columnWidth);
                    List<InventoryAlertVO> mainLPList = inventoryAlertMapper.findAllInventoryAlerts(inventoryAlertDTO);
                    resultBean.setRows(topTitles);
                    resultBean.setResult(mainLPList);
                    mainLPLs.add(resultBean);

                }
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }else{
            List<SiteVO> userSites = siteMapper.findUserSites(inventoryAlertDTO.getUserId());
            StringBuffer stringBuffer = new StringBuffer();
            for(SiteVO siteVO:userSites){
                inventoryAlertDTO.setSdId(siteVO.getSdId());
                String dataSourceName = "";
                String sdIdStr = siteVO.getSdId().toString();
                SiteData siteData = null;
                if(!IsEmptyUtils.isEmpty(jobj.get(sdIdStr))){
                    siteData = JSON.parseObject(jobj.get(sdIdStr).toString(),SiteData.class);
                }

                if(!IsEmptyUtils.isEmpty(siteData)){
                    dataSourceName = siteData.getDateSourceName();
                }
                if(!IsEmptyUtils.isEmpty(dataSourceName)){

                    logger.info("--"+siteData.getDateSourceName()+"--");

                    DynamicDataSourceContextHolder.setDataSourceType(dataSourceName);

                    inventoryAlertDTO.setSiteName(siteData.getName());

                    Map columnWidth = new HashMap();
                    columnWidth.put(0,5000);
                    columnWidth.put(1,4000);
                    columnWidth.put(2,4000);
                    columnWidth.put(3,3000);
                    columnWidth.put(4,5000);
                    columnWidth.put(5,15000);
                    List<List<String>> topTitles = Lists.newArrayList();
                    List<String> col0 = Lists.newArrayList();
                    List<String> col1 = Lists.newArrayList();
                    List<String> col2 = Lists.newArrayList();
                    List<String> col3 = Lists.newArrayList();
                    List<String> col4 = Lists.newArrayList();
                    List<String> col5 = Lists.newArrayList();
                    col0.add(exportTopTitle);col0.add("日期");
                    col1.add(exportTopTitle);col1.add("承担者昵称");
                    col2.add(exportTopTitle);col2.add("确认者名称");
                    col3.add(exportTopTitle);col3.add("状态");
                    col4.add(exportTopTitle);col4.add("处理时间");
                    col5.add(exportTopTitle);col5.add("异常描述");
                    topTitles.add(col0);
                    topTitles.add(col1);
                    topTitles.add(col2);
                    topTitles.add(col3);
                    topTitles.add(col4);
                    topTitles.add(col5);
                    ResultBean resultBean = new ResultBean();
                    resultBean.setMsg(siteData.getName());
                    resultBean.setObj(columnWidth);
                    List<InventoryAlertVO> mainLPList = inventoryAlertMapper.findAllInventoryAlerts(inventoryAlertDTO);
                    resultBean.setRows(topTitles);
                    resultBean.setResult(mainLPList);
                    mainLPLs.add(resultBean);
                }
            }
            DynamicDataSourceContextHolder.setDataSourceType(null);
        }
        return mainLPLs;
    }
}
